#!/bin/bash
# encoding:utf-8

CURDATE=${CURDATE:-$(date "+%Y-%m-%d_%H:%M:%S")}
LOGDIR=${LOGDIR:-logs}
PIDDIR=${PIDDIR:-.}
LOGFILENAME=${LOGDIR}/${LOGFILENAME:-$(basename $0 .sh).log}
PIDFILENAME=${PIDDIR}/${PIDFILENAME:-$(basename $0 .sh).pid}

## LOGLEVEL : DEBUG INFO WARN
LOGLEVEL=${LOGLEVEL:-DEBUG}

###################### START FUNCTIONS ###################
function log() {
	[ "$LOGLEVEL" \> "$1" ] && return
	A_LEVEL=$1
	shift
	MSG="$(LANG=C date '+%Y-%m-%d %H:%M:%S%z')\t$HOSTNAME\t$A_LEVEL\t$*"
	if [ -n "$LOGFILENAME" ] ; then
		echo -e "$MSG" >> $LOGFILENAME
	else
		echo -e "$MSG"
	fi
}

## log rotation when running this script
function log_rotation() {
	log "DEBUG" "INIT LOG"
	if [ -z "$LOGFILENAME" ] ; then
		return
	fi
	MAXSIZE="10240k" # logfile size 
	FIND=$(find $LOGDIR -type f -name "$(basename $LOGFILENAME)" -size +$MAXSIZE -print)
	if [ -z "$FIND" ] ; then
		log "DEBUG" "NO LOG ROTATION "
		return
	fi 
	mv $LOGFILENAME $LOGFILENAME.$DATE
	echo "" > $LOGFILENAME
	MAX=10 #keep generations 
	LC=$(ls $LOGFILENAME.* | wc -l)
	if [ "$LC" -lt "$MAX" ] ; then
		log "DEBUG" "NO DELETE LOG FILE"
		return 
	fi
	DELETENUM=$(($LC - $MAX))
	for f in `ls $LOGFILENAME.*|sort |head -$DELETENUM` ; do
		log "DEBUG" "DELETE LOG FILE $f"
		rm $f
	done
}

function duplicateRunCheck() {
	if [ -e $PIDFILENAME ] ; then
		if ps $(cat $PIDFILENAME) > /dev/null ; then
			log "INFO" "Already running ";
			exit;
		fi
	fi
	echo $$ > $PIDFILENAME
}
#//////////////////// initialization start ////////////////////
[ -e $LOGDIR ] || (mkdir -p $LOGDIR || log "WARN" "Can't mkdir $LOGDIR" && exit 1)
[ -e $PIDDIR ] || (mkdir -p $PIDDIR || log "WARN" "Can't mkdir $PIDDIR" && exit 1)
exec 2>&1
exec >> $LOGFILENAME

duplicateRunCheck
log_rotation
#//////////////////// initialization end   ////////////////////

#/////////////////// delete function definitions start ////////////////
unset log_rotation
unset duplicateRunCheck
#/////////////////// delete function definitions end   ////////////////

# vi:set ts=4 sw=4 sts=0 ai : 
